/**
 * Live GPS Tracking Application
 * Bluetooth GPS driver
 *
 * Copyright 2009, Ivar Clemens
 */

package nl.ivarclemens.gpsdriver;

import java.io.InputStream;
import java.io.IOException;
import javax.microedition.io.StreamConnection;
import java.io.ByteArrayOutputStream;
import javax.microedition.io.Connector;

public class Bluetooth implements Driver {

    private StreamConnection conn = null;
    private InputStream is = null;
    private ByteArrayOutputStream bos = null;

    private String btAddress;

    private boolean connected = false;

    public Bluetooth()
    {
        bos = new ByteArrayOutputStream();
    }

    public boolean isConnected()
    {
        return connected;
    }

    public boolean reconnect()
    {
        return openConnection(this.btAddress);
    }

    public boolean openConnection(String btAddress)
    {
        this.btAddress = btAddress;

        try {
            conn = (StreamConnection) Connector.open("btspp://" + btAddress + ":1", Connector.READ);
            is = conn.openInputStream();
        } catch(IOException exception) {
            return false;
        }

        connected = true;

        return true;
    }

    public String readMsg()
    {
        if(!connected)
            return "";

        String message = "";
        try {
            int ch;

            while((ch = is.read()) != -1) {

                if(ch == 10 || ch == 13) {
                    if(bos.size() > 0)
                        break;
                    else
                        continue;
                }

                bos.write(ch);
            }

            if(ch == -1)
                connected = false;

            message = bos.toString();
            bos.reset();
        } catch(IOException exception) {
            connected = false;
        }

        return message;
    }

    public void closeConnection()
    {
        try {
            if(is != null)
                is.close();

            if(conn != null)
               conn.close();
        } catch(IOException exception) {
        }

        connected = false;
    }
}
